// 俄罗斯方块游戏核心逻辑
class Tetris {
    constructor() {
        // 游戏配置
        this.cols = 10;
        this.rows = 20;
        this.blockSize = 30;
        
        // 游戏状态
        this.board = Array(this.rows).fill().map(() => Array(this.cols).fill(0));
        this.currentPiece = null;
        this.nextPiece = null;
        this.score = 0;
        this.lines = 0;
        this.level = 1;
        this.gameOver = false;
        this.paused = false;
        
        // 画布相关
        this.canvas = document.getElementById('tetris');
        this.ctx = this.canvas.getContext('2d');
        this.nextCanvas = document.getElementById('nextPiece');
        this.nextCtx = this.nextCanvas.getContext('2d');
        
        // 分数和行数显示
        this.scoreElement = document.getElementById('score');
        this.linesElement = document.getElementById('lines');
        this.levelElement = document.getElementById('level');
        
        // 游戏消息
        this.gameMessage = document.getElementById('gameMessage');
        this.messageText = document.getElementById('messageText');
        
        // 方块颜色定义
        this.colors = [
            null,          // 0: 空
            '#FF5252',     // 1: 红色
            '#4CAF50',     // 2: 绿色
            '#2196F3',     // 3: 蓝色
            '#FFC107',     // 4: 黄色
            '#9C27B0',     // 5: 紫色
            '#00BCD4',     // 6: 青色
            '#FF9800'      // 7: 橙色
        ];
        
        // 方块形状定义
        this.shapes = [
            [],  // 空
            [[0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, 0], [0, 0, 0, 0]],  // I 1
            [[2, 0, 0], [2, 2, 2], [0, 0, 0]],  // J 2
            [[0, 0, 3], [3, 3, 3], [0, 0, 0]],  // L 3
            [[4, 4], [4, 4]],  // O 4 
            [[0, 5, 5], [5, 5, 0], [0, 0, 0]],  // S 5
            [[0, 6, 0], [6, 6, 6], [0, 0, 0]],  // T 6
            [[7, 7, 0], [0, 7, 7], [0, 0, 0]]   // Z 7 
        ];
        
        // 初始化游戏
        this.resetGame();
    }
    
    // 重置游戏
    resetGame() {
        this.board = Array(this.rows).fill().map(() => Array(this.cols).fill(0));
        this.score = 0;
        this.lines = 0;
        this.level = 1;
        this.gameOver = false;
        this.paused = false;
        
        // 更新显示
        this.updateScore();
        
        // 生成第一个方块和下一个方块
        this.currentPiece = this.createPiece();
        this.nextPiece = this.createPiece();
        
        // 隐藏游戏消息
        this.gameMessage.classList.remove('show');
        
        // 绘制初始游戏状态
        this.drawBoard();
        this.drawNextPiece();
    }
    
    // 创建新方块
    createPiece() {
        const type = Math.floor(Math.random() * 7) + 1;
        const piece = {
            type: type,
            shape: this.shapes[type],
            x: Math.floor(this.cols / 2) - Math.floor(this.shapes[type][0].length / 2),
            y: 0
        };
        return piece;
    }
    
    // 检查碰撞
    checkCollision(piece, offsetX = 0, offsetY = 0) {
        for (let y = 0; y < piece.shape.length; y++) {
            for (let x = 0; x < piece.shape[y].length; x++) {
                if (piece.shape[y][x] !== 0) {
                    const newX = piece.x + x + offsetX;
                    const newY = piece.y + y + offsetY;
                    
                    if (
                        newX < 0 || 
                        newX >= this.cols || 
                        newY >= this.rows || 
                        (newY >= 0 && this.board[newY][newX] !== 0)
                    ) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    // 旋转方块
    rotatePiece() {
        const rotatedShape = [];
        const rows = this.currentPiece.shape.length;
        const cols = this.currentPiece.shape[0].length;
        
        // 创建旋转后的形状矩阵
        for (let i = 0; i < cols; i++) {
            rotatedShape[i] = [];
            for (let j = 0; j < rows; j++) {
                rotatedShape[i][j] = this.currentPiece.shape[rows - 1 - j][i];
            }
        }
        
        const tempShape = this.currentPiece.shape;
        const originalX = this.currentPiece.x;
        const originalY = this.currentPiece.y;
        
        // 尝试标准旋转
        this.currentPiece.shape = rotatedShape;
        
        // 如果旋转后发生碰撞，尝试墙踢（wall kick）
        if (this.checkCollision(this.currentPiece)) {
            // 尝试墙踢：向左移动1格
            this.currentPiece.x--;
            if (this.checkCollision(this.currentPiece)) {
                // 向左移动不行，尝试向右移动2格（恢复原位后再向右移动1格）
                this.currentPiece.x += 2;
                if (this.checkCollision(this.currentPiece)) {
                    // 向右移动不行，尝试向上移动1格
                    this.currentPiece.x = originalX;
                    this.currentPiece.y--;
                    if (this.checkCollision(this.currentPiece)) {
                        // 所有墙踢尝试都失败，恢复原状
                        this.currentPiece.shape = tempShape;
                        this.currentPiece.x = originalX;
                        this.currentPiece.y = originalY;
                    }
                }
            }
        }
        
        // 确保方块不会移动到游戏板左侧之外
        while (this.checkCollision(this.currentPiece)) {
            this.currentPiece.x++;
            if (this.currentPiece.x > this.cols) {
                // 如果无法避免碰撞，恢复原状
                this.currentPiece.shape = tempShape;
                this.currentPiece.x = originalX;
                this.currentPiece.y = originalY;
                break;
            }
        }
    }
    
    // 将当前方块固定到游戏板上
    lockPiece() {
        for (let y = 0; y < this.currentPiece.shape.length; y++) {
            for (let x = 0; x < this.currentPiece.shape[y].length; x++) {
                if (this.currentPiece.shape[y][x] !== 0) {
                    const boardY = this.currentPiece.y + y;
                    const boardX = this.currentPiece.x + x;
                    
                    // 检查游戏是否结束（方块任何部分超出游戏板顶部）
                    if (boardY < 0) {
                        this.gameOver = true;
                        return;
                    }
                    
                    this.board[boardY][boardX] = this.currentPiece.shape[y][x];
                }
            }
        }
        
        // 消行
        this.clearLines();
        
        // 检查是否游戏结束
        if (!this.gameOver) {
            // 使用下一个方块作为当前方块，并生成新的下一个方块
            this.currentPiece = this.nextPiece;
            this.nextPiece = this.createPiece();
            this.drawNextPiece();
            
            // 新增检查：如果新方块一出现就发生碰撞，游戏结束
            if (this.checkCollision(this.currentPiece)) {
                this.gameOver = true;
            }
        }
    }
    
    // 消行
    clearLines() {
        let linesCleared = 0;
        
        for (let y = this.rows - 1; y >= 0; y--) {
            if (this.board[y].every(cell => cell !== 0)) {
                // 移除已满的行
                this.board.splice(y, 1);
                // 在顶部添加新的空行
                this.board.unshift(Array(this.cols).fill(0));
                // 由于移除了一行，需要重新检查当前位置
                y++;
                linesCleared++;
            }
        }
        
        if (linesCleared > 0) {
            // 计算得分
            const linePoints = [0, 40, 100, 300, 1200]; // 0, 1, 2, 3, 4行的得分
            this.score += linePoints[linesCleared] * this.level;
            this.lines += linesCleared;
            
            // 检查是否升级
            this.level = Math.floor(this.lines / 10) + 1;
            
            // 更新显示
            this.updateScore();
        }
    }
    
    // 更新分数显示
    updateScore() {
        this.scoreElement.textContent = this.score;
        this.linesElement.textContent = this.lines;
        this.levelElement.textContent = this.level;
    }
    
    // 绘制游戏板
    drawBoard() {
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制网格背景
        this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
        for (let y = 0; y < this.rows; y++) {
            for (let x = 0; x < this.cols; x++) {
                this.ctx.strokeRect(x * this.blockSize, y * this.blockSize, this.blockSize, this.blockSize);
            }
        }
        
        // 绘制游戏板上已固定的方块
        for (let y = 0; y < this.rows; y++) {
            for (let x = 0; x < this.cols; x++) {
                const cell = this.board[y][x];
                if (cell !== 0) {
                    this.drawBlock(x, y, cell);
                }
            }
        }
        
        // 绘制当前方块
        if (this.currentPiece) {
            for (let y = 0; y < this.currentPiece.shape.length; y++) {
                for (let x = 0; x < this.currentPiece.shape[y].length; x++) {
                    if (this.currentPiece.shape[y][x] !== 0) {
                        const boardX = this.currentPiece.x + x;
                        const boardY = this.currentPiece.y + y;
                        if (boardY >= 0) { // 只绘制在游戏板内的部分
                            this.drawBlock(boardX, boardY, this.currentPiece.shape[y][x]);
                        }
                    }
                }
            }
        }
        
        // 如果游戏结束，显示游戏结束消息
        if (this.gameOver) {
            this.showMessage('游戏结束！按重置键重新开始');
        }
        
        // 如果游戏暂停，显示暂停消息
        if (this.paused) {
            this.showMessage('游戏暂停');
        }
    }
    
    // 绘制单个方块
    drawBlock(x, y, type) {
        // 绘制方块主体
        this.ctx.fillStyle = this.colors[type];
        this.ctx.fillRect(x * this.blockSize, y * this.blockSize, this.blockSize, this.blockSize);
        
        // 绘制方块边框
        this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(x * this.blockSize, y * this.blockSize, this.blockSize, this.blockSize);
        
        // 绘制方块高光效果
        this.ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
        this.ctx.fillRect(x * this.blockSize + 4, y * this.blockSize + 4, this.blockSize - 8, this.blockSize - 8);
    }
    
    // 绘制下一个方块预览
    drawNextPiece() {
        // 清空画布
        this.nextCtx.clearRect(0, 0, this.nextCanvas.width, this.nextCanvas.height);
        
        if (this.nextPiece) {
            const nextBlockSize = 24; // 下一个方块预览的方块大小
            const centerX = (this.nextCanvas.width - this.nextPiece.shape[0].length * nextBlockSize) / 2;
            const centerY = (this.nextCanvas.height - this.nextPiece.shape.length * nextBlockSize) / 2;
            
            // 绘制下一个方块
            for (let y = 0; y < this.nextPiece.shape.length; y++) {
                for (let x = 0; x < this.nextPiece.shape[y].length; x++) {
                    if (this.nextPiece.shape[y][x] !== 0) {
                        const drawX = centerX + x * nextBlockSize;
                        const drawY = centerY + y * nextBlockSize;
                        
                        // 绘制方块主体
                        this.nextCtx.fillStyle = this.colors[this.nextPiece.shape[y][x]];
                        this.nextCtx.fillRect(drawX, drawY, nextBlockSize, nextBlockSize);
                        
                        // 绘制方块边框
                        this.nextCtx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
                        this.nextCtx.lineWidth = 2;
                        this.nextCtx.strokeRect(drawX, drawY, nextBlockSize, nextBlockSize);
                        
                        // 绘制方块高光效果
                        this.nextCtx.fillStyle = 'rgba(255, 255, 255, 0.2)';
                        this.nextCtx.fillRect(drawX + 3, drawY + 3, nextBlockSize - 6, nextBlockSize - 6);
                    }
                }
            }
        }
    }
    
    // 显示游戏消息
    showMessage(text) {
        this.messageText.textContent = text;
        this.gameMessage.classList.add('show');
    }
    
    // 游戏主循环
    gameLoop() {
        if (!this.paused && !this.gameOver) {
            // 尝试下移方块
            if (!this.checkCollision(this.currentPiece, 0, 1)) {
                this.currentPiece.y++;
            } else {
                // 方块无法下移，固定到游戏板上
                this.lockPiece();
            }
            
            // 绘制游戏状态
            this.drawBoard();
        }
    }
    
    // 获取游戏状态（用于AI决策）
    getGameState() {
        return {
            board: this.board,
            currentPiece: this.currentPiece,
            nextPiece: this.nextPiece,
            cols: this.cols,
            rows: this.rows
        };
    }
    
    // 移动方块（用于AI控制）
    movePieceLeft() {
        if (!this.checkCollision(this.currentPiece, -1, 0)) {
            this.currentPiece.x--;
            this.drawBoard();
        }
    }
    
    movePieceRight() {
        if (!this.checkCollision(this.currentPiece, 1, 0)) {
            this.currentPiece.x++;
            this.drawBoard();
        }
    }
    
    movePieceDown() {
        if (!this.checkCollision(this.currentPiece, 0, 1)) {
            this.currentPiece.y++;
            this.drawBoard();
        } else {
            this.lockPiece();
            this.drawBoard();
        }
    }
    
    hardDrop() {
        while (!this.checkCollision(this.currentPiece, 0, 1)) {
            this.currentPiece.y++;
        }
        this.lockPiece();
        this.drawBoard();
    }
}